package cn.aezo.minions.web.controller;

import cn.aezo.minions.gen.model.ModuleFunction;
import cn.aezo.minions.gen.model.ProjectModule;
import cn.aezo.minions.gen.mapper.ModuleFunctionDao;
import cn.aezo.minions.gen.mapper.ProjectModuleDao;
import cn.aezo.minions.web.services.ModuleFunctionService;
import cn.aezo.minions.web.services.ProjectConfigService;
import cn.aezo.utils.base.ValidU;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by smalle on 2017/10/25.
 */
@RestController
@RequestMapping("/api")
public class ConfigController {
    @Autowired
    private ProjectModuleDao projectModuleDao;

    @Autowired
    private ModuleFunctionDao moduleFunctionDao;

    @Autowired
    private ProjectConfigService projectConfigService;

    @Autowired
    private ModuleFunctionService moduleFunctionService;

    @RequestMapping(path = "/projectModules")
    public Object findProjectModules(Long projectConfigId) {
        List<ProjectModule> projectModules = projectModuleDao.findByProjectConfigId(projectConfigId);

        return CommonController.layPage(projectModules);
    }

    @RequestMapping(path = "/moduleFunctions")
    public Object findModuleFunctions(Long projectModuleId) {
        List<ModuleFunction> moduleFunctions = new ArrayList<>();
        if(ValidU.isNotEmpty(projectModuleId)) {
            moduleFunctions = moduleFunctionDao.findByProjectModuleId(projectModuleId);
        }

        return CommonController.layPage(moduleFunctions);
    }

    @RequestMapping(path = "/projectModule", method = RequestMethod.POST)
    public Object editProjectModule(ProjectModule projectModule) {
        int id;
        Long projectModuleId = projectModule.getProjectModuleId();
        if(ValidU.isEmpty(projectModuleId)) {
            // 新增
            id = projectModuleDao.insert(projectModule);
        } else {
            id = projectModuleDao.update(projectModule);
        }

        return id;
    }

    @RequestMapping(path = "/projectModule/{projectModuleId}", method = RequestMethod.POST)
    public Object editProjectModule(@PathVariable Long projectModuleId) {
        int id = 0;
        if(ValidU.isNotEmpty(projectModuleId)) {
            id = projectModuleDao.delete(projectModuleId);
        }

        return id;
    }

    @RequestMapping(path = "/initModule", method = RequestMethod.POST)
    public Object initModule(Long projectConfigId) {
        return projectConfigService.initModule(projectConfigId);
    }

    @RequestMapping(path = "/initFunction", method = RequestMethod.POST)
    public Object initFunction(Long projectConfigId) {
        return moduleFunctionService.initFunction(projectConfigId);
    }

}
